package com.example.monotarr;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class EditaTasca extends Main {
	
	private String titol;
	private String notes;
	private int prioritat;
	private int hora;
	private int minut;
	private int dia;
	private int mes;
	private int any;
	private boolean data;
	private boolean time;
	private int marcat;
	private int id;
	private int mode; //-1 duplica   0 edita
	private AlertDialog segur;
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.edita_tasca);
		
		
		
		this.but.setVisibility(View.GONE);
		this.but2.setVisibility(View.GONE);
		this.but3.setVisibility(View.GONE);
		
		ListView lv = getListView();
		lv.setVisibility(View.GONE);
		
		Bundle extras = getIntent().getExtras();
		if(extras !=null) {
			id = extras.getInt("id");
			mode = extras.getInt("mode");
			
			if (mode == 0) {
				Button nom = (Button) findViewById(R.id.button1);
				nom.setText("Edita tasca");
				this.title2.setText("Edita la tasca");
			}
			else if (mode == -1) {
				Button esborra = (Button) findViewById(R.id.buttonX);
				esborra.setVisibility(View.GONE);
				Button nom = (Button) findViewById(R.id.button1);
				nom.setText("Duplica tasca");
				this.title2.setText("Duplica la tasca");
			}
		
		}		
		
        usdbh = new ListSQLiteHelper(this, "DBList", null, 1);	            
        SQLiteDatabase db = usdbh.getWritableDatabase();
           
        String[] camps = new String[] {"titol", "notes", "prioritat", "dia", "mes", "any", "hora", "minut", "marcat"};  
		
        Cursor aux;
        aux = db.query("List", camps, id+" = id", null, null, null, null);
        aux.moveToFirst();      
        
        titol = aux.getString(0);
        notes = aux.getString(1);
        prioritat = aux.getInt(2);
        dia = aux.getInt(3);
        mes = aux.getInt(4);
        any = aux.getInt(5);
        hora = aux.getInt(6);
        minut = aux.getInt(7);
        marcat = aux.getInt(8);
        aux.close();
		db.close();
				
		if (dia == 99) data = false;
		else data = true;
		
		if (hora == 99) time = false;
		else time = true;
		

		
		
		
		EditText tit = (EditText) findViewById(R.id.editText1);
		EditText not = (EditText) findViewById(R.id.editText2);
		tit.setText(titol);
		not.setText(notes);
		
		
		RadioButton alta = (RadioButton) findViewById(R.id.alta);
		RadioButton mitjana = (RadioButton) findViewById(R.id.mitjana);
		RadioButton baixa = (RadioButton) findViewById(R.id.baixa);
		
		if (prioritat == 1) alta.setChecked(true);
		else if (prioritat == 2) mitjana.setChecked(true);
		else if (prioritat == 3) baixa.setChecked(true);

		
		
		//checkbox Date
	    CheckBox cbDate = (CheckBox) findViewById(R.id.checkBox1);
	    
	    if (data) {
	    	cbDate.setChecked(true);
    		TextView text = (TextView) findViewById(R.id.textView4);
    		text.setText(dia+"/"+mes+"/"+any);
	    }
	    else cbDate.setChecked(false);
	    
	    cbDate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

	     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
	            if ( isChecked ) { 
	            		data = true;
	            		showDialog(1);
	            }
	            else {
	            	data = false;
	        		TextView text = (TextView) findViewById(R.id.textView4);
	        		text.setText("");
	            }
	            
	     }
	    });
	    
	    
		//checkbox Time
	    CheckBox cbTime = (CheckBox) findViewById(R.id.checkBox2);
	    
	    if (time) {
	    	cbTime.setChecked(true);
			String s = hora + ":";
			if (minut < 10) s+= "0";
							
    		TextView text = (TextView) findViewById(R.id.textView5);
    		text.setText(s+minut);
	    }
	    else cbTime.setChecked(false);
	    
	    cbTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

	     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
	            if ( isChecked ) {
	            		time = true;
	            		showDialog(0);
	            }
	            else {
	            	time = false;
	        		TextView text = (TextView) findViewById(R.id.textView5);
	        		text.setText("");
	            }
	     }
	    });
		
		Button b2 = (Button) findViewById(R.id.button2);
		b2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
		        finish();
	    		Intent intent = new Intent();
	    		intent.setClass(EditaTasca.this, Main.class);
	    		startActivity(intent);				

			}
		});
	   	
		
		
		
		segur = new AlertDialog.Builder(this).create();
		segur.setTitle("Segur que vols esborrar aquesta tasca?");

		segur.setButton("D'acord", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
	    		esborraBD_id(id);
	    		
	            finish();            
	            
	    		Intent intent = new Intent();
	    		intent.setClass(EditaTasca.this, Main.class);
	    		startActivity(intent);
				Toast.makeText(EditaTasca.this,
						"Tasca esborrada",
						Toast.LENGTH_SHORT).show();
				return;
			}
		});

		segur.setButton2("Cancel·la", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
		
		
		
		
		
		
		
		
		
	} /////FI ON CREATE	

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	        finish();
    		Intent intent = new Intent();
    		intent.setClass(EditaTasca.this, Main.class);
    		startActivity(intent);
	        
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	
	
	private TimePickerDialog.OnTimeSetListener TimeListener =
			new TimePickerDialog.OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int h, int m) {
		
				hora = h;
				minut = m;
				
				String s = h + ":";
				if (m < 10) s+= "0";
								
        		TextView text = (TextView) findViewById(R.id.textView5);
        		text.setText(s+m);
        		

			}

			
	};
	
	
	

	private DatePickerDialog.OnDateSetListener DateListener =
			new DatePickerDialog.OnDateSetListener() {
			public void onDateSet(DatePicker view, int a, int m, int d) {	
				any = a;
				mes = m + 1;
				dia = d;
        		TextView text = (TextView) findViewById(R.id.textView4);
        		text.setText(dia+"/"+mes+"/"+any);
				
			}
	};
	
			
	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance(); 
			switch (id) {
			case 0:
				
				TimePickerDialog timer = new TimePickerDialog(this, TimeListener, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
				//timer.setMessage("Escull una hora");
				
				timer.setButton(DatePickerDialog.BUTTON_POSITIVE, "Defineix", timer);
			
			    timer.setButton(DialogInterface.BUTTON_NEGATIVE,
			    		"Cancel·la",
			            new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int which) {
			    				CheckBox cbt = (CheckBox) findViewById(R.id.checkBox2);
			    	        	cbt.setChecked(false);
			                }
			            });
			    


				return timer;
			case 1:
				DatePickerDialog dater = new DatePickerDialog(this, DateListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
				//dater.setMessage("Escull una data");
				
				
				dater.setButton(DatePickerDialog.BUTTON_POSITIVE, "Defineix", dater);
				
			    dater.setButton(DialogInterface.BUTTON_NEGATIVE,
			    		"Cancel·la",
			            new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int which) {
			    				CheckBox cbd = (CheckBox) findViewById(R.id.checkBox1);
			    	        	cbd.setChecked(false);
			                }
			            });

			    
				
				

				return dater;
			}	
			
			return null;
	}
		
	
    public void guarda2(View view) {
    	switch (view.getId()) {
	    	case R.id.button1:
	    		
	    		
	    		
	    		EditText tit = (EditText) findViewById(R.id.editText1);
	    		EditText not = (EditText) findViewById(R.id.editText2);
	    		titol = tit.getText().toString();
	    		notes = not.getText().toString();
	    		
	    		/*int prioritatINT;
	    		if (prioritat.equals("Alta")) prioritatINT = 1;
	    		else if (prioritat.equals("Mitjana")) prioritatINT = 2;
	    		else prioritatINT = 3;*/
	    		
	    		Calendar cal = Calendar.getInstance();
	    		 
	    		
	    		if (titol.length() == 0) {
	    			Toast.makeText(EditaTasca.this, "Si us plau, afegeix un títol com a mínim", Toast.LENGTH_SHORT).show();
	    		}
	    		else if (data && (any < cal.get(Calendar.YEAR) || 
	    				(any == cal.get(Calendar.YEAR) && mes < cal.get(Calendar.MONTH) + 1) ||
	    				(any == cal.get(Calendar.YEAR) && mes == (cal.get(Calendar.MONTH) + 1) && dia < cal.get(Calendar.DAY_OF_MONTH)) ||
	    				(any == cal.get(Calendar.YEAR) && mes == (cal.get(Calendar.MONTH) + 1) && dia == cal.get(Calendar.DAY_OF_MONTH) && time && hora < cal.get(Calendar.HOUR_OF_DAY)) ||
	    				(any == cal.get(Calendar.YEAR) && mes == (cal.get(Calendar.MONTH) + 1) && dia == cal.get(Calendar.DAY_OF_MONTH) && time && hora == cal.get(Calendar.HOUR_OF_DAY) && minut < cal.get(Calendar.MINUTE)) 
	    				)) {
	    			Toast.makeText(EditaTasca.this, "Data passada", Toast.LENGTH_SHORT).show();
	    		}
	    		else {
	    		
		    		if (!time) {
		    			hora = 99;
		    			minut = 99;
		    		}
		    		
		    		if (!data) {
		    			dia = 99;
		    			mes = 99;
		    			any = 9999;
		    		}
		    		
		    		int prioritatINT;
		    		RadioButton alta = (RadioButton) findViewById(R.id.alta);
		    		RadioButton mitjana = (RadioButton) findViewById(R.id.mitjana);
		    		
		    		if (alta.isChecked()) prioritatINT = 1;
		    		else if (mitjana.isChecked()) prioritatINT = 2;
		    		else prioritatINT = 3;
		    		
		    		//DB

		    		if (mode == 0) {
	    			
						usdbh = new ListSQLiteHelper(this, "DBList", null, 1);	            
						SQLiteDatabase db = usdbh.getWritableDatabase();
						if(db != null) {
		    				db.execSQL("UPDATE List SET titol = '" + titol + "', notes = '" + notes + 
		    						"', prioritat = " + prioritatINT +", dia = " + dia +", mes = " + mes +
		    						", any = " + any + ", hora = " + hora + ", minut = " + minut + " WHERE id = "+ id);
		    				
						}
						db.close();
						Toast.makeText(EditaTasca.this, "Tasca editada", Toast.LENGTH_SHORT).show();
						
		    		}
	            	else if (mode == -1){
			    		usdbh = new ListSQLiteHelper(this, "DBList", null, 1);	            
			            SQLiteDatabase db2 = usdbh.getWritableDatabase();
			            if(db2 != null) {
			            	Integer aa = lastID + 1;
			            	Log.v("AAA",aa+"");
			                db2.execSQL("INSERT INTO List (id, titol, notes, prioritat, dia, mes, any, hora, minut, marcat) " +
		                               "VALUES ("+ aa.toString() + ",'" + titol + "', '" + notes +"', " + prioritatINT +  ", " + dia + ", " + mes + ", " + any + ", " + hora + ", " + minut + ", " + marcat+")");
		               
		               
			                db2.execSQL("UPDATE LastID SET lastid = " + aa.toString());
			            }
		                db2.close();
		                
		                Toast.makeText(EditaTasca.this, "Tasca duplicada", Toast.LENGTH_SHORT).show();
	            	}
		                
		    		
		           

		            
		            //actualitzaBD();	  	           
		            finish();            
		            
		    		Intent intent = new Intent();
		    		intent.setClass(EditaTasca.this, Main.class);
		    		startActivity(intent);
		    	
	    		}
	
	    		break;
    	}
    	
    	
    }
    
    
    public void esborra(View view) {
    	switch (view.getId()) {
	    	case R.id.buttonX:

	    		segur.show();
	    	
	    	break;
    	}
    	
    	
    }
	
	
	


    
    
}
